package com.tools.cleanmaster.controller;

import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.item.FileTrashItem;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.MimeTypeUtil;
import com.tools.cleanmaster.utils.TrashMimeTypes;

import java.io.File;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by lianzhan on 15/12/30.
 */
public class LargeFileScanner extends TrashScanner {
    public static final String DB_NAME_EXTERNAL = "external";
    public static final long LARGE_FILE_THRESHOLD = 1024 * 1024 * 10; // 10MB

    private Context mContext;

    public LargeFileScanner(Context context, TrashHandler handler) {
        super(context, handler);
        this.mContext = context;
    }

    @Override
    public void scan(int increaseProgress) {
        if (!mIsScanning) {
            mIsScanning = true;
            scanMediaLargeFile(increaseProgress);
            mIsScanning = false;
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void scanMediaLargeFile(int increaseProgress) {
        Cursor cursor = null;
        long totalSize = 0;

        try {
            ContentResolver contentResolver = mContext.getContentResolver();
            cursor = contentResolver.query(MediaStore.Files.getContentUri(DB_NAME_EXTERNAL),
                    new String[] {MediaStore.Files.FileColumns.DATA, MediaStore.Files.FileColumns.SIZE,
                            MediaStore.Files.FileColumns._ID
                    }, MediaStore.Files.FileColumns.SIZE + " >= " + LARGE_FILE_THRESHOLD, null, null);

            if (cursor == null) {
                return;
            }

            int count = cursor.getCount();
            if (count == 0) {
                return;
            }

            while (cursor.moveToNext()) {

                if (mStopRequested) {
                    return;
                }

                String path = cursor.getString(0);
                if (TextUtils.isEmpty(path)) {
                    continue;
                }

                String mime = MimeTypeUtil.getMimeType(path);
                if (TextUtils.isEmpty(mime)) {
                    continue;
                }
                if (mime.startsWith(MimeTypeUtil.VIDEO) || mime.startsWith(MimeTypeUtil.IMAGE)) {
                    continue;
                }

                long size = cursor.getLong(1);
                long id = cursor.getLong(2);
                File file = new File(path);
                if (new File(path).exists()) {
                    totalSize += size;
                    createTrashItemLargeFile(file, path, size, id);
                }
            }

            List<TrashItem> largeList = mTrashesData.getTrashesByType(TrashType.LARGE_FILE);
            if (largeList != null) {
                Collections.sort(largeList, new Comparator<TrashItem>() {
                    @Override
                    public int compare(TrashItem lhs, TrashItem rhs) {
                        if (lhs.size < rhs.size) {
                            return 1;
                        } else if (lhs.size > rhs.size) {
                            return -1;
                        }
                        return 0;
                    }
                });
            }

        } catch (Exception e) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.e(SUB_TAG, "scanMediaLargeFile", e);
            }
        } finally {
            mTrashHandler.updateProgress(increaseProgress, null);
            mTrashHandler.onTrashTypeFinish(TrashType.LARGE_FILE, totalSize);
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private void createTrashItemLargeFile(File f, String path, long size, long id) {
        FileTrashItem trash = new FileTrashItem();
        trash.id = id;
        trash.trashType = TrashType.LARGE_FILE;
        trash.mFileName = f.getName();
        trash.lastModified = f.lastModified();
        trash.mFileType = TrashMimeTypes.getFileTypes(trash.mFileName);
        trash.filePath = path;
        trash.fileCount = 1;
        trash.size = size;
        trash.isSelectedDefault = trash.isSelected = false;
        if (!mStopRequested) {
            mTrashesData.putTrash(TrashType.LARGE_FILE, trash);
        }
        if (FeatureConfig.DEBUG_LOG) {
            LogHelper.v(SUB_TAG, "[trash_large] filePath:" + trash.filePath + " size:" + size);
        }
    }
}
